class Solution:
    def validUtf8(self, data: list) -> bool:
        i, length = 0, len(data)
        try:
            while i < length:
                mid_str = self.my_bin(data[i])
                index = mid_str.index("0")
                if index > 4 or index == 1:
                    return False
                elif 1 < index <= 4:
                    for j in range(i + 1, i + index):
                        mid_str2 = self.my_bin(data[j])
                        if not mid_str2.startswith("10"):
                            return False
                    i += index
                else:
                    i += 1
        except:
            return False
        else:
            return True

    def my_bin(self, i: int) -> str:
        if i > 255:
            raise IndexError
        return bin(i)[2:].rjust(8, "0")


a = Solution()
print(a.validUtf8([197, 130, 1]))
print(a.validUtf8([235, 140, 4]))
